package com.example.my.nanyibangz.ui.dapei;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.my.nanyibangz.R;
import com.example.my.nanyibangz.base.BaseFragment;
import com.example.my.nanyibangz.bean.DaPeiDownBean;
import com.example.my.nanyibangz.bean.DaPeiUpBean;
import com.example.my.nanyibangz.config.DaPeiDownUrlConfig;
import com.example.my.nanyibangz.config.DaPeiUrlConfig;
import com.example.my.nanyibangz.ui.dapeiclick.DaPeiClickActivity;
import com.example.my.nanyibangz.ui.dapeidownclick.DaPeiDownClickActivity;
import com.example.my.nanyibangz.utils.CustomGridView;
import com.example.my.nanyibangz.utils.CustomerNestScrollView;
import com.example.my.nanyibangz.utils.ExStaggeredGridLayoutManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 马伟大大的
 * 辛苦遭逢起一经，干戈寥落四周星!
 * Created by My on 2016/10/5.
 * 搭配
 */
public class DaPeiFragment extends BaseFragment implements DaPeiUpContact.View {

    int page = 1;
    @Bind(R.id.toolbar_dapei)
    Toolbar toolbarDapei;
    @Bind(R.id.gv_groupUp)
    CustomGridView gvGroupUp;
    @Bind(R.id.gv_groupDown)
    RecyclerView gvGroupDown;
    @Bind(R.id.tv_warn)
    TextView tvWarn;
    @Bind(R.id.layout_footer)
    LinearLayout layoutFooter;
    @Bind(R.id.scro_dapei)
    CustomerNestScrollView scroDapei;
    @Bind(R.id.sr_dapei)
    SwipeRefreshLayout srDapei;
    private DaPeiUpContact.Presenter presenter;
    private List<DaPeiUpBean.DataBean.ItemsBean> itemsBeen;
    private List<DaPeiDownBean.DataBean> dataBeanList;
    DaPeiDownAdapter adapters;
    DaPeiRecAdapter recAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dapei, null);
        ButterKnife.bind(this, view);
        //gvGroupDown.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        gvGroupDown.setLayoutManager(new ExStaggeredGridLayoutManager(2,ExStaggeredGridLayoutManager.VERTICAL));
        //ScrollView 滑动顺滑
        gvGroupDown.setNestedScrollingEnabled(false);
        initView();
        initLoad();
        initData(page);

        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //gvGroupDown.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        SwipRefresh();
        ScrollBottom();
        Click();

    }

    //tooBar设置
    private void initView() {
        //fragment中不能使用setSupportActionBar（）方法，想使用必须继承AppCompatActivity。
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbarDapei);//设置toolbar
        toolbarDapei.setTitle("");
        activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_dp);//更改toolbar的返回按钮图片
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);//设置toolbar的返回安妮可以使用
    }

    private void initLoad() {
        presenter = new DaPeiUpPresenter(this);
        //http://api.nanyibang.com/match-classify?age=19&channel=oppo&hkm_sign2=f6ebc7b34f32060cea1a6e5d7acb5d5a&member_id=292720&member_type=member&random_key=30170&sys  tem_name=android&versionCode=219
        Map<String, String> map = new HashMap<>();
        map.put(DaPeiUrlConfig.Params.Age, DaPeiUrlConfig.DefaultVaule.Age_VALUE);
        map.put(DaPeiUrlConfig.Params.Channel, DaPeiUrlConfig.DefaultVaule.Channel_VALUE);
        map.put(DaPeiUrlConfig.Params.Hkm_sign2, DaPeiUrlConfig.DefaultVaule.Hkm_sign2_VALUE);
        map.put(DaPeiUrlConfig.Params.Member_id, DaPeiUrlConfig.DefaultVaule.Member_id_VALUE);
        map.put(DaPeiUrlConfig.Params.Member_type, DaPeiUrlConfig.DefaultVaule.Member_type_VALUE);
        map.put(DaPeiUrlConfig.Params.Random_key, DaPeiUrlConfig.DefaultVaule.Random_key_VALUE);
        map.put(DaPeiUrlConfig.Params.System_name, DaPeiUrlConfig.DefaultVaule.System_name_VALUE);
        map.put(DaPeiUrlConfig.Params.VersionCode, DaPeiUrlConfig.DefaultVaule.VersionCode_VALUE);
        presenter.getVerticalFromNet_DaPeiUp(map);
    }

    private void initData(int page) {
        //presenter = new DaPeiUpPresenter(this);
        //DaPeiDown
        Map<String, String> mapTwo = new HashMap<>();
        mapTwo.put(DaPeiDownUrlConfig.Params.Age, DaPeiDownUrlConfig.DefaultVaule.Age_VALUE);
        mapTwo.put(DaPeiDownUrlConfig.Params.Channel, DaPeiDownUrlConfig.DefaultVaule.Channel_VALUE);
        mapTwo.put(DaPeiDownUrlConfig.Params.Page, page + "");
        mapTwo.put(DaPeiDownUrlConfig.Params.System_name, DaPeiDownUrlConfig.DefaultVaule.System_name_VALUE);
        mapTwo.put(DaPeiDownUrlConfig.Params.VersionCode, DaPeiDownUrlConfig.DefaultVaule.System_name_VALUE);
        presenter = new DaPeiUpPresenter(this);
        presenter.getVerticalFrmNet_DaPeiDown(mapTwo);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onVerticalSucess_DaPeiBeanUp(List<DaPeiUpBean.DataBean> itemsBeanList) {
        DaPeiUpAdapter adapter = new DaPeiUpAdapter(getActivity(), itemsBeanList.get(0).getItems());
        gvGroupUp.setAdapter(adapter);
        // daPeiUpBeans=itemsBeanList.get()
        itemsBeen = itemsBeanList.get(0).getItems();
    }

    @Override
    public void onVerticalFail_DaPei(String msg) {

    }

    @Override
    public void onVerticalSucess_DaPeiBeanDown(List<DaPeiDownBean.DataBean> beanList) {
        Log.i("tag", "beanlist===========" + beanList.size());
        if (beanList.size() != 0) {
            if (page == 1) {
                dataBeanList = beanList;
                layoutFooter.setVisibility(View.GONE);
                recAdapter=new DaPeiRecAdapter(getActivity(),dataBeanList);
                gvGroupDown.setAdapter(recAdapter);
                 DownClick();
            } else {
                dataBeanList.addAll(beanList);//追加
                recAdapter.notifyDataSetChanged();
            }


        } else {
            tvWarn.setText("没有更多数据啦！");
        }
    }

    @Override
    public void onVerticalFail_DaPeiDown(String msg) {
        Log.i("tag", "fail===========");
    }
    //下拉刷新
    private void SwipRefresh() {

        srDapei.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorSwipRef));
        srDapei.setColorSchemeResources(R.color.color_holo_yellow, R.color.color_holo_green, R.color.color_holo_he, R.color.color_holo_he2);
        srDapei.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        srDapei.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("tag", "datalist============" + dataBeanList.size());
                        recAdapter=new DaPeiRecAdapter(getActivity(),dataBeanList);
                        gvGroupDown.setAdapter(recAdapter);
                        srDapei.setRefreshing(false);
                    }
                }, 3000);
            }
        });
    }
    //上拉刷新的事件
    private void ScrollBottom() {
        scroDapei.setOnScrollToBottomLintener(new CustomerNestScrollView.OnScrollToBottomListener() {
            @Override
            public void onScrollBottomListener(boolean isBottom) {
                if (isBottom == true) {
                    layoutFooter.setVisibility(View.VISIBLE);
                    initData((++page));
                }
            }
        });
    }

    //上半部分的点击事件
    private void Click() {
        gvGroupUp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                int classify_id = itemsBeen.get(position).getClassifyId();
                String classify_name = itemsBeen.get(position).getClassifyName();
                Intent intent = new Intent(getActivity(), DaPeiClickActivity.class);
                intent.putExtra("classify_id", classify_id);
                intent.putExtra("classify_name", classify_name);
                startActivity(intent);
            }
        });

    }

    //下半部分的点击事件
    private void DownClick() {
        recAdapter.setItemClickListener(new DaPeiRecAdapter.OnItemActionListener() {
            @Override
            public void OnItemClick(View view, String CollocationId) {
                Intent intent = new Intent(getActivity(), DaPeiDownClickActivity.class);
                intent.putExtra("collocation_id", CollocationId);
                startActivity(intent) ;
            }
        });
    }
}
